<template>
  <div class="app-container">
    <div class="app-container-flex">
      <!-- 字典表格 -->
      <div class="left-container">
        <!-- 条件栏 -->
        <new-page-filter
          v-model:query="dictFilterInfo.query"
          :filter-list="dictFilterInfo.searchList"
          :filter-btn="dictFilterInfo.searchBtn"
        >
          <template v-slot:filter-nameLike>
            <el-input
              v-model="dictFilterInfo.query.nameLike"
              placeholder="请输入字典名称或编码"
              clearable
              @keyup.enter="dictSearch(dictTableInfo.copyData)"
            />
          </template>
          <template v-slot:filter-button>
            <el-button @click="dictSearch(dictTableInfo.copyData)"
              >搜索</el-button
            >
          </template>
        </new-page-filter>
        <new-page-filter :filter-btn="dictFilterInfo.btnList">
          <template v-slot:filter-deleteDict>
            <el-button
              :disabled="!dictTableInfo.tableCheckRows.length"
              @click="deleteDict"
              >删除</el-button
            >
          </template>
        </new-page-filter>
        <div class="left-container-main main-flex">
          <!-- 表格 -->
          <table-container
            ref="dictTable"
            :refresh="dictTableInfo.refresh"
            :init-curpage="dictTableInfo.initCurpage"
            v-model:data="dictTableInfo.data"
            :api="getDictTree"
            :pager="false"
            row-key="id"
            :expands="dictTableInfo.expands"
            :tab-index="dictTableInfo.tabIndex"
            :highlight-row="true"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :query="dictFilterInfo.query"
            :field-list="dictTableInfo.fieldList"
            :row-class-name="rowClassName"
            @handleEvent="handleEvent"
          ></table-container>
        </div>
      </div>
      <!-- 字典项表格 -->
      <div class="right-container" style="paddingtop: 34px">
        <!-- 条件栏 -->
        <new-page-filter
          v-model:query="dictItemFilterInfo.query"
          :filter-btn="dictItemFilterInfo.list"
        >
          <!-- 新增按钮 -->
          <template v-slot:filter-showCreateDictItem>
            <el-button :disabled="dictItemDisable" @click="showCreateDictItem"
              >新增</el-button
            >
          </template>
        </new-page-filter>
        <!-- 表格 -->
        <table-container
          :refresh="dictItemTableInfo.refresh"
          :init-curpage="dictItemTableInfo.initCurpage"
          v-model:data="dictItemTableInfo.data"
          :api="dictItemTableInfo.api"
          :pager="false"
          :check-box="false"
          :load-data="dictItemTableInfo.loadData"
          :query="dictItemFilterInfo.query"
          :field-list="dictItemTableInfo.fieldList"
          :handle="dictItemTableInfo.handle"
          class="right-table-container"
        ></table-container>
      </div>
      <!-- 新增修改弹窗 -->
      <page-dialog
        v-if="dictDialogInfo.visible"
        :title="dictDialogInfo.title[dictDialogInfo.type]"
        v-model:visible="dictDialogInfo.visible"
        :width="dictDialogInfo.width"
        :bt-loading="dictDialogInfo.btLoading"
        :bt-list="dictDialogInfo.btList"
      >
        <!-- form -->
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="dictFormInfo.ref"
          :data="dictFormInfo.data"
          :field-list="dictFormInfo.fieldList"
          :rules="dictFormInfo.rules"
          :label-width="dictFormInfo.labelWidth"
        />
      </page-dialog>
      <!-- 新增修改弹窗 -->
      <page-dialog
        v-if="dictItemDialogInfo.visible"
        :title="dictItemDialogInfo.title[dictItemDialogInfo.type]"
        v-model:visible="dictItemDialogInfo.visible"
        :width="dictItemDialogInfo.width"
        :bt-loading="dictItemDialogInfo.btLoading"
        :bt-list="dictItemDialogInfo.btList"
      >
        <!-- form -->
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="dictItemFormInfo.ref"
          :data="dictItemFormInfo.data"
          :field-list="dictItemFormInfo.fieldList"
          :rules="dictItemFormInfo.rules"
          :label-width="dictItemFormInfo.labelWidth"
        />
      </page-dialog>
    </div>
  </div>
</template>

<script setup name="dict">
import {
  getDictAll,
  getDictItemAll,
  delDict,
  delDictItem,
  createDict,
  updateDict,
  createDictItem,
  updateDictItem,
  getDictTree,
  setDefaultDictItem
} from '@/api/base.js'
const { proxy } = getCurrentInstance()

const dictIdIn = ref(undefined)
const dictId = ref(undefined)
// 过滤相关配置
const dictFilterInfo = ref({
  query: {
    nameLike: '',
    sort: 'create_time desc',
  },
  searchList: [
    {
      //componentType: "input",
      slot: true,
      label: '名称',
      //event: dictSearch,
      value: 'nameLike',
    },
  ],
  searchBtn: [{ value: 'button', type: 'slot', show: true }], //type: "button", label: "搜索", event: dictSearch }],
  btnList: [
    {
      type: 'button',
      label: '新增',
      btType: 'primary',
      event: showCreateDict,
      show: false,
    },
    { value: 'deleteDict', type: 'slot', show: false },
  ],
})
const dictItemFilterInfo = ref({
  query: {
    nameLike: '',
    sort: 'dict_id desc',
  },
  list: [
    {
      type: 'slot',
      value: 'showCreateDictItem',
      show: true,
    },
  ],
})
// 字典表格相关
const dictTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  tableCheckRows: [],
  data: [],
  expands: [],
  copyData: [],
  tabIndex: false,
  fieldList: [
    { label: '字典名称', value: 'name', align: 'left' },
    { label: '字典编码', value: 'code' },
    { label: '字典类型', value: 'dictTypeValue' },
  ],
  // handle: {
  //   fixed: false,
  //   label: '操作',
  //   width: '100',
  //   btList: [
  //     {
  //       label: '添加下级',
  //       event: addChild,
  //       show: true,
  //       ifRender: ifRender,
  //     },
  //     {
  //       label: '修改',
  //       event: showUpdateDict,
  //       show: true,
  //       ifRender: ifRender,
  //     },
  //     {
  //       label: '删除',
  //       event: deleteDict,
  //       show: true,
  //       ifRender: ifRender,
  //       popconfirmText: '删除后将改变数据,是否继续？',
  //     },
  //   ],
  // },
})
// 字典项表格相关
const dictItemTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  loadData: false,
  fieldList: [
    { label: '字典项名称', value: 'name' },
    { label: '字典项编码', value: 'code' },
    { label: '是否默认', value: 'isDefaultValue' },
    { label: '字典类型', value: 'dictTypeValue' },
    { label: '是否启用', value: 'isEnableValue' },
    { label: '顺序', value: 'sort' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '启用',
        event: enableDictItem,
        show: true,
        ifRender: ifRenderEnable,
      },
      {
        label: '停用',
        event: enableDictItem,
        show: true,
        ifRender: ifRenderDisable,
      },
      {
        label: '设置默认',
        event: setDefault,
        show: true,
        ifRender: ifRenderSetDefault,
      },
      {
        label: '修改',
        event: showUpdateDictItem,
        show: true,
        ifRender: ifRenderItem,
      },
      {
        label: '删除',
        event: deleteDictItem,
        show: true,
        ifRender: ifRenderItem,
        popconfirmText: '删除后将改变数据,是否继续？',
      },
    ],
  },
})
// 字典表单相关
const dictFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '父级节点',
      type: 'input',
      value: 'parentName',
      disabled: true,
    },
    { label: '名称', value: 'name', type: 'input' },
    { label: '编码', value: 'code', type: 'input', disabled: false },
    { label: '顺序', value: 'sort', type: 'number' },
    {
      label: '字典类型',
      value: 'dictType',
      type: 'select-model',
      disabled: true,
      code: 'dict_type',
      checkDefault: true,
    },
    {
      label: '描述',
      value: 'description',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入顺序', trigger: 'blur' }],
    code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 表单相关
const dictItemFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '名称',
      value: 'name',
      type: 'input',
      maxlength: 200,
    },
    {
      label: '编码',
      value: 'code',
      type: 'number',
      min: 1,
      disabled: false,
    },
    {
      label: '顺序',
      value: 'sort',
      type: 'number',
    },
    {
      label: '默认',
      value: 'isDefault',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '字典类型',
      value: 'dictType',
      type: 'select-model',
      disabled: true,
      code: 'dict_type',
      checkDefault: true,
    },
    {
      label: '是否启用',
      value: 'isEnable',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入顺序', trigger: 'blur' }],
    code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 字典弹窗相关
const dictDialogInfo = ref({
  title: {
    createDict: '新增',
    updateDict: '修改',
    createDictChild: '添加下级',
  },
  visible: false,
  type: '',
  data: {},
  btLoading: false,
  btList: [
    { label: '关闭', event: closeDict, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveDict,
      saveLoading: false,
      show: true,
    },
  ],
})
// 字典项弹窗相关
const dictItemDialogInfo = ref({
  title: {
    createDict: '添加',
    updateDict: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', event: closeDictItem, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveDictItem,
      saveLoading: false,
      show: true,
    },
  ],
})
const dictItemDisable = ref(true)
// 获取列表
function getList() {
  dictTableInfo.value.refresh = Math.random()
}
function showCreateDict() {
  //打开字典弹窗
  let index = dictFormInfo.value.fieldList.findIndex(
    (item) => item.value === 'parentName'
  )
  let codeIndex = dictFormInfo.value.fieldList.findIndex(
    (item) => item.value === 'code'
  )
  if (index !== -1) {
    dictFormInfo.value.fieldList[index].show = false
  }
  if (codeIndex !== -1) {
    dictFormInfo.value.fieldList[codeIndex].disabled = false
  }
  dictFormInfo.value.data = {
    parentId: -1,
  }
  dictDialogInfo.value.type = 'createDict'
  dictDialogInfo.value.visible = true
}
// function addChild(row) {
//   //打开字典弹窗
//   let index = dictFormInfo.value.fieldList.findIndex(
//     (item) => item.value === 'parentName'
//   )
//   let codeIndex = dictFormInfo.value.fieldList.findIndex(
//     (item) => item.value === 'code'
//   )
//   if (index !== -1) {
//     dictFormInfo.value.fieldList[index].show = true
//   }
//   if (codeIndex !== -1) {
//     dictFormInfo.value.fieldList[codeIndex].disabled = false
//   }
//   dictFormInfo.value.data = {
//     parentName: row.name,
//     parentId: row.id,
//   }
//   dictDialogInfo.value.type = 'createDictChild'
//   dictDialogInfo.value.visible = true
// }
function dictSearch() {
  // 字典搜索
  getList()
}
function getNodeId(list, newNodeId = []) {
  for (let i in list) {
    newNodeId.push(list[i].id + '')
    if (list[i].children) {
      getNodeId(list[i].children, newNodeId)
    }
  }
  return newNodeId
}
function searchFromChildren(children, searchValue) {
  for (let i in children) {
    if (
      String(children[i].name).indexOf(searchValue) > -1 ||
      String(children[i].code).indexOf(searchValue) > -1
    ) {
      return true
    } else if (children[i].children && children[i].children.length) {
      return searchFromChildren(children[i].children, searchValue)
    } else {
      return false
    }
  }
}
function searchFromList(list, searchValue) {
  let arr = []
  for (let i in list) {
    if (
      String(list[i].name).indexOf(searchValue) > -1 ||
      String(list[i].code).indexOf(searchValue) > -1 ||
      searchFromChildren(list[i].children, searchValue)
    ) {
      arr.push(list[i])
    }
  }
  return arr
}
// function showUpdateDict(data = undefined) {
//   let index = dictFormInfo.value.fieldList.findIndex(
//     (item) => item.value === 'parentName'
//   )
//   let codeIndex = dictFormInfo.value.fieldList.findIndex(
//     (item) => item.value === 'code'
//   )

//   if (index !== -1) {
//     dictFormInfo.value.fieldList[index].show = true
//   }
//   if (codeIndex !== -1) {
//     dictFormInfo.value.fieldList[codeIndex].disabled = true
//   }

//   dictFormInfo.value.data = { ...data }
//   dictDialogInfo.value.type = 'updateDict'
//   dictDialogInfo.value.visible = true
// }
function closeDict() {
  //关闭字典弹窗
  dictDialogInfo.value.visible = false
  dictFormInfo.value.data = {}
}
function closeDictItem() {
  dictItemDialogInfo.value.visible = false
  dictItemFormInfo.value.data = {}
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      proxy.$refs['dictTable'].setCurrentRow(data[0])
      if (dictFilterInfo.value.query.nameLike && data.length) {
        proxy.$nextTick(() => {
          dictTableInfo.value.expands = getNodeId(data)
        })
      } else {
        proxy.$nextTick(() => {
          dictTableInfo.value.expands = []
        })
      }
      break
    case 'tableCheck':
      proxy.$nextTick(() => {
        dictTableInfo.value.tableCheckRows = data
      })
      break
    case 'tableClickRow':
      proxy.$nextTick(() => {
        dictClickRow(data)
      })
      break
  }
}
function rowClassName(data) {
  return 'tableCell' + data.rowIndex
}
function showCreateDictItem() {
  let codeIndex = dictItemFormInfo.value.fieldList.findIndex(
    (item) => item.value === 'code'
  )
  if (codeIndex !== -1) {
    dictItemFormInfo.value.fieldList[codeIndex].disabled = false
  }
  dictItemFormInfo.value.data = {}
  dictItemDialogInfo.value.type = 'createDict'
  dictItemDialogInfo.value.visible = true
}
function showUpdateDictItem(data) {
  let codeIndex = dictItemFormInfo.value.fieldList.findIndex(
    (item) => item.value === 'code'
  )
  if (codeIndex !== -1) {
    dictItemFormInfo.value.fieldList[codeIndex].disabled = true
  }
  dictItemDialogInfo.value.type = 'updateDict'
  dictItemFormInfo.value.data = { ...data }
  dictItemDialogInfo.value.visible = true
}
function enableDictItem(data) {
  // 启停用
  const params = { ...data }
  params.isEnable = params.isEnable === 1 ? 0 : 1
  updateDictItem(params).then((res) => {
    if (res && res.success) {
      dictItemTableInfo.value.refresh = Math.random()
    }
  })
}
function setDefault(data) {
  // 设置默认
  setDefaultDictItem(data).then((res) => {
    if (res && res.success) {
      dictItemTableInfo.value.refresh = Math.random()
    }
  })
}

function saveDict() {
  const _dictDialogInfo = dictDialogInfo.value
  const _dictTableInfo = dictTableInfo.value
  const _dictFormInfo = dictFormInfo.value
  dictFormInfo.value.ref.validate((valid) => {
    if (valid) {
      const params = _dictFormInfo.data
      const api = params.id ? updateDict : createDict
      api(params).then((res) => {
        if (res && res.success) {
          _dictDialogInfo.visible = false
          _dictTableInfo.refresh = Math.random()
          _dictFormInfo.data = {}
        }
      })
    }
  })
}
function saveDictItem() {
  const _dictItemDialogInfo = dictItemDialogInfo.value
  const _dictItemTableInfo = dictItemTableInfo.value
  const _dictItemFormInfo = dictItemFormInfo.value
  dictItemFormInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const params = _dictItemFormInfo.data
      const type = _dictItemDialogInfo.type
      if (type === 'createDict') {
        params.dictIdIn = dictIdIn.value
        params.dictId = dictId.value
        api = createDictItem
      } else if (type === 'updateDict') {
        api = updateDictItem
      } else {
        return
      }
      _dictItemDialogInfo.btLoading = true
      api(params)
        .then((res) => {
          if (res && res.success) {
            _dictItemDialogInfo.visible = false
            _dictItemTableInfo.refresh = Math.random()
            _dictItemFormInfo.data = {}
          }
          _dictItemDialogInfo.btLoading = false
        })
        .catch((e) => {
          _dictItemDialogInfo.btLoading = false
        })
    }
  })
}
//字典表格点击按钮
function dictClickRow(row) {
  if (!row) {
    return
  }
  if (row.dictType === 0) {
    dictItemDisable.value = true
  } else {
    dictItemDisable.value = false
  }
  dictIdIn.value = row['dictIdIn']
  dictId.value = row['id']
  dictItemFilterInfo.value.query.dictIdIn = row.dictIdIn
  dictItemTableInfo.value.api = getDictItemAll
  dictItemTableInfo.value.refresh = Math.random()
}
function deleteDict(row = undefined) {
  if (row && row.id) {
    deleteItem([row.id])
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
      .then(() => {
        let ids = dictTableInfo.value.tableCheckRows.map((item) => item.id)
        deleteItem(ids)
      })
  }
}
function deleteItem(ids) {
  delDict(ids).then((res) => {
    if (res && res.success) {
      getList()
      dictItemTableInfo.value.data = []
    }
  })
}
function deleteDictItem(row = undefined) {
  const _dictItemTableInfo = dictItemTableInfo.value
  const ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids.push(
      _dictItemTableInfo.tableCheckRows.map(function (row) {
        return row.id
      })
    )
  }
  delDictItem(ids).then((res) => {
    if (res && res.success) {
      _dictItemTableInfo.refresh = Math.random()
    }
  })
}
function ifRenderItem(row) {
  return row.dictType
}
function ifRenderAddItem(row) {
  let cur_data = dictTableInfo.value.data.filter((d) => d.id == this.dictIdIn)
  return cur_data.length ? cur_data[0].dictType : false
}
function ifRenderEnable(row) {
  return row.isEnable !== 1
}
function ifRenderDisable(row) {
  return row.isEnable === 1
}
function ifRenderSetDefault(row) {
  return row.isDefault === 0
}

</script>

<style lang="scss" scoped>
.left-container {
  min-width: 600px;
  max-width: 600px;
  .page-filter {
    padding: 2px;
  }
}
.right-container {
  width: calc(100% - 640px);
  .page-filter {
    padding: 5px 5px;
  }
  // .right-table-container {
  //   padding: 0 20px;
  // }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 51px);
  .table-container {
    // width: 100%;
    // overflow-y: hidden;
    // position: relative;
    // display: block;
  }
}
.el-table__indent {
  padding-left: 16px;
}
</style>
